package com.kady.service.impl;

import com.kady.Dao.FoodDao;
import com.kady.Dao.FoodTypeDao;
import com.kady.Dao.OrderDao;
import com.kady.Dao.TableDao;
import com.kady.contant.BeanFactoryConstant;
import com.kady.entity.*;
import com.kady.factory.BeanFactory;
import com.kady.service.FrontService;
import com.kady.service.TableService;
import com.kady.utils.JdbcUtil;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/3/30
 * \* Time: 13:06
 * \* 千峰JAVA2101班
 * \* Description: 前台业务层
 * \
 */
public class FrontServiceImpl implements FrontService {
    private TableDao tableDao = (TableDao) BeanFactory.getBean(BeanFactoryConstant.TABLE_DAO);
    private FoodDao foodDao = (FoodDao) BeanFactory.getBean(BeanFactoryConstant.FOOD_DAO);
    private FoodTypeDao foodTypeDao = (FoodTypeDao) BeanFactory.getBean(BeanFactoryConstant.FOODTYPE_DAO);
    private OrderDao orderDao = (OrderDao) BeanFactory.getBean(BeanFactoryConstant.ORDER_DAO);

    private TableService tableService = (TableService)BeanFactory.getBean(BeanFactoryConstant.TABLE_SERVICE);

    /**
     * 根据状态获取餐桌列表
     */
    @Override
    public List<Table> getTableListByStatus() throws SQLException {
        List<Table> res = tableDao.selectTableListByStatus((byte)0);
        return res;
    }

    /**
     * 查看用户是否有已下单的订单
     */
    @Override
    public Order findUserHasNotOrdered(Object user) throws SQLException {
        Order res = orderDao.selectOrderByUserId(((User)user).getUser_id());
        return res;
    }

    /**
     * 查询用户下是否有未结账的订单
     */


    @Override
    public PageInfo getFoodListByCondition(String keyword,PageInfo pageInfo, String typeId) throws SQLException, InvocationTargetException, IllegalAccessException {
        /**
         * 获取菜品列表
         */
        List<Map<String, Object>> maps = foodDao.selectFoodList(keyword, pageInfo, typeId);
        List<Food> foodList = new ArrayList<>();
        for(Map<String,Object> item:maps){
//            Food food = new Food((String)item.get("foodName"), (double)item.get("price") , (double)item.get("vipPrice") , (long)item.get("typeId") , (String)item.get("foodImage") , (String)item.get("foodDesc") , foodType);
            Food food = new Food();
            BeanUtils.populate(food,item);
            FoodType foodType = new FoodType(Long.valueOf(item.get("typeId").toString()),(String)item.get("typeName"));
            food.setFoodType(foodType);
            foodList.add(food);
        }

        pageInfo.setData(foodList);

        /**
         * 获取数据总条数
         */
        long count = foodDao.calListCount(keyword,typeId);
        pageInfo.setTotalCount(count);
        return pageInfo;
    }

    /**
     * 获取菜系列表
     */
    @Override
    public List<FoodType> getFoodTypeList() throws SQLException {
        List<FoodType> foodTypes = foodTypeDao.selectFoodTypeList("%%");
        return foodTypes;
    }

    /**
     * 获取单个菜品信息
     */
    @Override
    public Food getFoodDetail(String foodId) throws SQLException {
        Food food = foodDao.selectFood(foodId);
        return food;
    }

    /**
     * 用于更新餐车数据，iscreate用于判断是否是加入餐车，
     * true代表加入餐车，count为加的数量，false代表修改餐车，count为赋值数量
     */
    @Override
    public Cart updateCart(Cart cart,String foodId,User user,long count,boolean isCreate) throws SQLException {
        /**
         * 查询餐车中是否已有要添加的菜品,有找到就给数量+1
         */
        boolean isHas = false;
        List<CartItem> cartItems =  cart.getCartItems();
        if(cartItems!=null){
            for(CartItem item:cartItems){
                if(item!=null && item.getFoodId()==Long.valueOf(foodId)){
                    if(count==0){
                        cartItems.remove(item);
                        break;
                    }
                    if(isCreate){
                        item.setCount(item.getCount()+count);
                    }else{
                        item.setCount(count);
                    }
                    isHas = true;
                }
            }
        }else{
            cartItems = new ArrayList<CartItem>();
        }

        //没有找到就加入一个菜品项
        if(isCreate && !isHas){
            CartItem cartItem = getCartItem(foodId,user);
            //菜品小计通过实体get方法自动计算
            cartItems.add(cartItem);
        }

        /**
         * 计算餐车总价和数量
         */
        cart.setCartItems(cartItems);
        cart.setTotalPrice(calCartTotalPrice(cartItems));
        cart.setTotalCount(calCartTotalCount(cartItems));
        return cart;
    }



    /**
     * 通过菜品ID获取菜品信息，用户的is——vip来判断是否用会员价
     */
    @Override
    public CartItem getCartItem(String foodId,User user) throws SQLException {
        Food food = foodDao.selectFood(foodId);
        //获得菜品详情,如果是VIP用户就存储会员价，否则就存普通价格
        CartItem cartItem = new CartItem(Long.valueOf(foodId),1, user.getIs_vip()==1?food.getVipPrice(): food.getPrice(),food);
        return cartItem;
    }

    /**
     * 计算餐车总价
     */
    @Override
    public double calCartTotalPrice(List<CartItem> cartItems) {
        double itemsTotalPrice = 0;
        for(CartItem item:cartItems){
            itemsTotalPrice+=item.getItemTotalPrice();
        }
        return itemsTotalPrice;
    }

    /**
     * 计算餐车菜品总数
     */
    @Override
    public long calCartTotalCount(List<CartItem> cartItems) {
        long itemsTotalCount = 0;
        for(CartItem item:cartItems){
            itemsTotalCount+=item.getCount();
        }
        return itemsTotalCount;
    }

    /**
     * 下单（创建订单）
     */
    @Override
    public void setOrder(String orderId,User user, String tableId, Cart cart) {
        try{
            JdbcUtil.begin();
            orderDao.addOrder(orderId,user, tableId, cart);
            List<CartItem> cartItems = cart.getCartItems();
            for(CartItem item:cartItems){
                orderDao.addOrderDeatilItem(orderId, Long.toString(item.getFoodId()), item);
            }
            //更改餐桌状态
            tableService.updateStatus(tableId);
            JdbcUtil.commit();
        }catch (Exception e){
            JdbcUtil.rollback();
            e.printStackTrace();
        }
    }

    /**
     * 订单结账
     */
    @Override
    public long settleOrder(String orderId) throws SQLException {
        long res = 0;
        try{
            JdbcUtil.begin();
            res =  orderDao.updateStatus(1,orderId);
            /**
             * 结账之后，获取桌号，改为空闲状态
             */
            Order order = orderDao.selectById(orderId);
            tableDao.update(0,null,order.getTableId());
            JdbcUtil.commit();
            return res;
        }catch (Exception e){
            JdbcUtil.rollback();
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 查订单详情列表 获取已下单的订单详情菜品
     */
    @Override
    public Cart getOrderCart(String orderId, User user) throws SQLException, InvocationTargetException, IllegalAccessException {
        List<Map<String, Object>> maps = orderDao.selectDetailList(orderId);
        Cart cart = new Cart();
        List<CartItem> cartItems = new ArrayList<>();
        for(Map<String, Object> item:maps){
            Food food = new Food();
            BeanUtils.populate(food,item);
            CartItem cartItem = new CartItem(Long.valueOf(String.valueOf(item.get("foodId"))),Long.valueOf(String.valueOf(item.get("count"))),(double)(user.getIs_vip()==1?item.get("vipPrice"):item.get("price")),food);
            cartItems.add(cartItem);
        }
        cart.setCartItems(cartItems);
        cart.setTotalPrice(calCartTotalPrice(cartItems));
        cart.setTotalCount(calCartTotalCount(cartItems));
        return cart;
    }
}
